<?php

namespace Cps\Controller;

use Think\Controller;
use Think\Crypt;

class ManageController extends Controller {

    private $cpsModel;

    public function __construct() {
        parent::__construct();
        session("[start]");
        if (!isset($_SESSION['cpsinfo']) || $_SESSION['cpsinfo']['id'] < 1) {
            $this->redirect('Login/index');
        }
        $this->cpsModel = new \Cps\Model\CpsmemberModel();
    }

    public function index() {
        $this->display();
    }

    public function add() {
        $cpsinfo = $_SESSION['cpsinfo'];
        $pid = $cpsinfo['id'];
        $cpsid = intval($_REQUEST['id']);
        if (IS_POST) {
            $username = I('post.username');
            $password = I('post.password');
            if ($cpsid == 0) {//如果cpsid==0说明是添加操作 否则为修改操作
                $cps = $this->cpsModel->getByCpsUser($username);
                if ($cps) {
                    $this->error("公会已存在！", U("index/index"));
                } else {
                    $data['username'] = $username;
                    $data['password'] = Crypt::Crypt_Hash_Create($password);
                    $data['pid'] = $pid;
                    if ($this->cpsModel->data($data)->add()) {
                        $this->success("公会添加成功！", U("index/index"));
                    } else {
                        $this->error("公会添加失败！", U("index/index"));
                    }
                }
            } else {
                $data['username'] = $username;
                $cps = $this->cpsModel->where("id='%d'", array($cpsid))->find();
                if ($cps) {
                    if ($cps['password'] == $password) {
                        $data['password'] = $password;
                    } else {
                        $data['password'] = Crypt::Crypt_Hash_Create($password);
                    }
                    if ($this->cpsModel->where("id='%d'", array($cpsid))->save($data)) {
                        $this->success("公会修改成功！", U("index/index"));
                    } else {
                        $this->error("公会修改失败！", U("index/index"));
                    }
                }else{
                    $this->error("系统忙请稍后在试！", U("index/index"));
                }
            }
        }
        if ($cpsid) {
            //修改操作
            $cps = $this->cpsModel->where("id='%d'", array($cpsid))->find();
            $this->assign('id', $cpsid);
            $this->assign('username', $cps['username']);
            $this->assign('password', $cps['password']);
        }
        $this->assign('pid', $pid);
        $this->display();
    }

}
